﻿using System.Reflection;
using System.Reflection.Emit;
using rpc_service.cache;
using rpc_service.core.support.assembly.il.http.get;
using rpc_service.core.support.assembly.il.http.post;

namespace rpc_service.core.support.assembly.il;

public class ILGenerate : RPCGenerate<ILStep>
{
    private ILGenerateMethod _ilGenerateMethod = new ILGenerateMethod();
    private RPCMethodLoader _rpcMethodLoader = new RPCMethodLoader();

    public ILGenerate() 
    {
        _steps = new ILStep[]
        {
            new ILSynchronizationGetHttpRequest(),
            new ILSynchronizationPostHttpRequest(),
            new ILGenerateReturn()
        };
    }

    public override object Generate(Type targetType)
    {
        // 定义动态程序集和模块
        AssemblyName assemblyName = new AssemblyName("DynamicRpcProxy");
        AssemblyBuilder assemblyBuilder =
            AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicRpcProxyModule");

        // 定义动态类型
        TypeBuilder typeBuilder = moduleBuilder.DefineType("DynamicRpcProxy",
            TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass |
            TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout, "object".GetTypeByStr(), new[] { targetType });

        foreach (var targetMethod in targetType.GetMethods())
        {
            if (!_rpcMethodLoader.MethodLoader(targetMethod))
            {
                continue;
            }

            _ilGenerateMethod.CreateRPCMethod(typeBuilder, targetType, targetMethod, _steps);
        }
        
        // 创建类型
        Type dynamicType = typeBuilder.CreateType();

        // 创建实例
        return Activator.CreateInstance(dynamicType)!;
    }
}